package com.zyx.crawlerdemo.jsonparse.orgjson.parse;

import com.zyx.crawlerdemo.jsonparse.model.BookModel1;

import java.lang.reflect.Field;

/**
 * @author Yaxi.Zhang
 * @since 2021/8/12 10:23
 * desc: 反射基本案例
 */
public class FieldStudy {


    public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        BookModel1 book = new BookModel1();
        book.setId("07");
        book.setLanguage("Java");
        book.setEdition("third");
        book.setAuthor("Herbert Schildt");
        //获取 Class对象
        Class cls = book.getClass();
        System.out.println(cls);

        /*
        	返回一个 Field对象,反映此 Class对象所表示的类或接口的指定公共成员字段。
    		注意这里如果使用getField("author")则会产生报错,原因是author是私有变量
		 */

        Field field1 = cls.getField("id");
        System.out.println("Public field found: " + field1.toString());
        //共有变量和私有变量皆可行
        Field field2 = cls.getDeclaredField("author");
        System.out.println("Public and Private field found: " + field2.toString());
        //getDeclaredFields()
        System.out.println("getDeclaredFields()结果为:");
        Field[] fieldarr1 = cls.getDeclaredFields();
        for (Field field : fieldarr1) {
            System.out.println("Public and Private field found: " + field.toString());
        }
        // getFields()
        System.out.println("getFields()结果为:");
        Field[] fieldarr2 = cls.getFields();
        for (Field field : fieldarr2) {
            System.out.println("Public field found: " + field.toString());
        }
        // 获取属性值
        Object object = field1.get(book);
        System.out.println(object);
        // 获取类型对象
        Class<?> classTest = field1.getType();
        System.out.println(classTest);
    }

}
